import { Tree, Modal, Button, message, Space } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import DetailForm from './components/DetailForm';
import { ExclamationCircleOutlined, PlusOutlined } from '@ant-design/icons';
import styles from './style.less';
const { confirm } = Modal;
import { queryArea, addArea, updateArea, removeArea, queryAreaTree } from '@/services/area';



const updateState = async (id:number,state:number) => {
  try {
    await updateArea({areaId:id,useState:state==0?1:0});
    return true;
  } catch (error) {
    return false;
  }
};

/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: any) => {
  const hide = message.loading('正在添加');
  try {
    await addArea(fields);
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: any) => {
  const hide = message.loading('正在保存');
  try {
    await updateArea(fields);
    hide();

    message.success('保存成功');
    return true;
  } catch (error) {
    hide();
    message.error('保存失败请重试！');
    return false;
  }
};




const Department: React.FC = () => {
  const [parentId, setParentId] = useState<string | number>('0');

  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [detailModalVisible, handleDetailModalVisible] = useState<boolean>(false);
  const [formValues, setFormValues] = useState({});
  const [selectedRowsState, setSelectedRows] = useState<API.AreaItem[]>([]);

  const [expandedKeys, setExpandedKeys] = useState<string[]>(['0']);
  const [treeData, setTreeData] = useState();
  const actionRef = useRef<ActionType>();

  const onSelect = (keys: React.Key[], info: any) => {
    setParentId(info.node.key)

    if (actionRef.current) {
      actionRef.current.reload();
    }
  };

  const onExpand = (e) => {
    setExpandedKeys(e);
    console.log(e);
    console.log('Trigger Expand');
  };


  const columns: ProColumns<API.AreaItem>[] = [

    {
      title: '区域名称',
      dataIndex: 'areaName',
      render: (_,record) => 
      <a
        onClick={async () => {
        handleDetailModalVisible(true);
        console.log(record)
        setFormValues(record);
      }}
      >{_}</a>,
    }, {
      title: '区域描述',
      search: false,
      dataIndex: 'areaDesc',
      width:300,
      // render: (text) => (
      //   <Space style={{width:'200px'}}>
      //      {text}
      //   </Space>
      // ),
    },
    {
      title: '上级区域名称',
      search: false,
      dataIndex: 'parentName',

    },
    {
      title: '是否启用',
      dataIndex: 'useState',
      valueType: 'radio',
      valueEnum: {
        1: { text: '启用' },
        0: { text: '禁用' },
      }
    },

    // {
    //   title: '创建时间',
    //   search: false,
    //   dataIndex: 'createTime',
    // },
    {
      title: '更新时间',
      search: false,
      dataIndex: 'updateTime',

    },



    {
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={async () => {
            handleUpdateModalVisible(true);
            // await queryTreeData();
            setFormValues(record);
          }}
        >
          编辑
        </a>,
          <a
          key="updateState"
          onClick={async () => {
           var resultState= await updateState( record.areaId,record.useState);
           if(resultState)
             actionRef.current?.reload();
          }}
          >
          {record.useState==0?'启用':'禁用'} 
          </a>,
        <a onClick={async () => { 
          const success =  await remove(record); 
       
        
       
         
        }}  >删除</a>


      ],
    },
  ];

  async function queryTreeData() {
    let trees = await queryAreaTree({ "type": "root" });
    //let trees = await queryAreaTree();
    console.log(trees)
    setTreeData(trees);
  }
  useEffect(() => {
    queryTreeData();

  }, []);

//删除单个
const toremove = async (areaId: number) => {
  const hide = message.loading('正在删除');
  try {
    await removeArea({areaId});
    hide();
    message.success('删除成功，正在刷新！');
    queryTreeData();
    return true;
  } catch (error) {
    hide();
    message.error('删除失败请重试！');
    return false;
  }
};


const remove = async (fields: any) => {

 
  if(fields.hasDevice!=null&&fields.hasChild!=null){
    message.error('当前区域下有添加的设备和子区域，请先删除！');
    return false;
  }
 if(fields.hasDevice!=null){
    message.error('当前区域下有添加的设备，请先删除设备！');
    return false;
  }
  if(fields.hasChild!=null){
    message.error('当前区域下有子区域，请先删除子区域！');
    return false ;
  }
  confirm({
    title: '您确定要删除吗?',
    icon: <ExclamationCircleOutlined />,
    async onOk() {
      await toremove(fields.areaId);
      actionRef.current?.reload();
      return true;
    },
    onCancel() {
      return false;
      console.log('Cancel');
    },
  });
 
};

  return (
    <div className={styles.main}>
      <div className={styles.leftMenu}>
        <Space direction="vertical" style={{ width: '90%' }}>
          {treeData!=null? 
          <Tree
           autoExpandParent
            
           defaultExpandedKeys={['0']}
           expandedKeys={expandedKeys}
            onSelect={onSelect}
            onExpand={onExpand}
            treeData={treeData}
          />:<></>}
       
        </Space>
      </div>
      <div className={styles.right}>
      <ProTable
        rowKey="areaId"
        toolBarRender={(action, { selectedRows }) => [
          <Button icon={<PlusOutlined />} type="primary"  className={styles.addBtn}   onClick={() => handleModalVisible(true)}>
            新增
          </Button>
        ]}
        actionRef={actionRef}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
        tableAlertRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => (
          <Space size={24}>
            <span>
              已选 {selectedRowKeys.length} 项
              <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                取消选择
              </a>
            </span>
          </Space>
        )}
        search={{
          labelWidth: 'auto',
        }}
        options={false}
        columns={columns}
        request={(params) => queryArea({ ...params, parentId: parentId })}
      />
      <CreateForm
        onSubmit={async (value) => {
          const success = await handleAdd(value);
          if (success) {
            handleModalVisible(false);
            queryTreeData();
            setParentId(parentId);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
        treeData={treeData}
        parentId={parentId}
      />
      {formValues && Object.keys(formValues).length ? (
        <UpdateForm
          onSubmit={async (value) => {
            const success = await handleUpdate(value);
            if (success) {
              handleModalVisible(false);
              queryTreeData();
              setFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={formValues}
          treeData={treeData}
        />
        
      ) : null}
       {formValues && Object.keys(formValues).length ? (
        <DetailForm
          onCancel={() => {
            handleDetailModalVisible(false);
            setFormValues({});
          }}
          updateModalVisible={detailModalVisible}
          values={formValues}
        />
      ) : null}
    </div>
    </div>
  );
};

export default Department;